package com.qianfeng.android.baoman.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.CinemaListActivity;
import com.qianfeng.android.baoman.Constants;
import com.qianfeng.android.baoman.MainActivity;
import com.qianfeng.android.baoman.R;
import com.qianfeng.android.baoman.adapter.MovieAdapter;
import com.qianfeng.android.baoman.model.Cinema;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class MovieFragment extends Fragment implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {

    private MainActivity context;
    //網絡加載失敗提示信息
    private LinearLayout load_layout;

    private List<Cinema> cinemaList;
    private MovieAdapter adapter;
    private View image_error;

    //代表当前的页数，刷新后页数加1
    private int pageCount;
    private PullToRefreshListView pullToRefreshView;

    private Handler handler = new Handler();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity != null) {
            context = (MainActivity) activity;
        }
    }

    public MovieFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_movie, container, false);
        context.setActionBarTitle("暴影院");
        image_error = view.findViewById(R.id.movie_image_error);
        image_error.setOnClickListener(this);

        load_layout = (LinearLayout) view.findViewById(R.id.load_layout);

        //下载按钮
        ImageButton downImage = (ImageButton) context.findViewById(R.id.action_function);
        downImage.setVisibility(View.VISIBLE);
        downImage.setImageResource(R.drawable.comic_load_btn);

        //处理上拉加载，下拉刷新
        pullToRefreshView = (PullToRefreshListView) view.findViewById(R.id.movie_listView);

        ListView listView = pullToRefreshView.getRefreshableView();
        pullToRefreshView.setMode(PullToRefreshBase.Mode.BOTH);
        cinemaList = new LinkedList<>();
        adapter = new MovieAdapter(cinemaList, context);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        Drawable drawable = getResources().getDrawable(R.drawable.arrow_down);
        pullToRefreshView.setLoadingDrawable(drawable);
        // 设置加载中的标题
        pullToRefreshView.setRefreshingLabel("加载...");
        // 设置“松开”提醒
        pullToRefreshView.setReleaseLabel("松开可以刷新");
        pullToRefreshView.setOnRefreshListener(this);

        pageCount = 1;
        loadData(Constants.getMovieIndexUrl(null, pageCount, 10));
        return view;
    }

    //加载数据
    public void loadData(String url) {
        load_layout.setVisibility(View.VISIBLE);
        pullToRefreshView.setVisibility(View.VISIBLE);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        String result = objectResponseInfo.result;
                        try {
                            //结束刷新
                            pullToRefreshView.onRefreshComplete();
                            JSONObject object = new JSONObject(result);
                            int total_pages = object.getInt("total_pages");
                            int per_page = object.getInt("per_page");
                            int page = object.getInt("page");
                            if (pageCount > total_pages) {
                                Toast.makeText(context, "已到底部", Toast.LENGTH_SHORT).show();
                                load_layout.setVisibility(View.GONE);
                                image_error.setVisibility(View.GONE);
                                return;
                            }
                            int total_count = object.getInt("total_count");
                            JSONArray cinemas = object.getJSONArray("cinema");

                            for (int i = 0; i < cinemas.length(); i++) {
                                JSONObject jsonObject = cinemas.getJSONObject(i);
                                Cinema cinema = new Cinema();
                                cinema.parseJSON(jsonObject);
                                if (!cinemaList.contains(cinema)) {
                                    cinemaList.add(cinema);
                                }
                            }
                            adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        load_layout.setVisibility(View.GONE);
                        image_error.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(context, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                        image_error.setVisibility(View.VISIBLE);
                        pullToRefreshView.setVisibility(View.GONE);
                        load_layout.setVisibility(View.GONE);
                        pullToRefreshView.setMode(PullToRefreshBase.Mode.DISABLED);
                        pageCount = 1;
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.movie_image_error:
                image_error.setVisibility(View.GONE);
                loadData(Constants.MOVIE_INDEX_URL);
                break;
        }
    }

    //上拉刷新
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = Constants.getMovieIndexUrl(null, 1, 10);

//        cinemaList.clear();
                loadData(url);
                pullToRefreshView.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }, 1000);
    }

    //下拉加载
    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pageCount++;
                String url = Constants.getMovieIndexUrl(null, pageCount, 10);
                loadData(url);
            }
        }, 1000);
        pageCount++;
        String url = Constants.getMovieIndexUrl(null, pageCount, 10);
        loadData(url);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cinema cinema = cinemaList.get(position - 1);
        Intent intent = new Intent(context, CinemaListActivity.class);
        intent.putExtra("cinema", cinema);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {


        Log.e("MovieFragment", "onDestroy");
        super.onDestroy();
    }
}
